import React, { useEffect, useState } from 'react';
import router from 'umi/router';
import {
  Table, Modal, Form, Input, Col, message, Switch, Select, DatePicker,
} from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import RenderButtom from '@/components/RenderButton';
import SearchBox from '@/components/SearchBox'
import {
  fetchContract,
} from '@/services/rentCenter/contract';
import { connect } from 'dva';
import { formItemLayout } from '@/utils/utils';

const hasSearchBtn = JSON.parse(localStorage.getItem('hasSearchBtn'))
const { Option } = Select
const { RangePicker } = DatePicker

const types = ['草稿', '待审批', '审批未通过', '正常', '已终止', '已到期']
const statsList = [
  {
    label: '草稿',
    value: '0',
  },
  {
    label: '待审批',
    value: '1',
  },
  {
    label: '审批未通过',
    value: '2',
  },
  {
    label: '正常',
    value: '3',
  },
  {
    label: '已终止',
    value: '4',
  },
  {
    label: '已到期',
    value: '5',
  },
]
const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
  },
  {
    title: '商铺号',
    key: 'contractShopsList',
    render: params => (
      <span>{params.join()}</span>
    ),
  },
  {
    title: '品牌',
    key: 'busContractStore',
    render: params => (
      <span>{params.brandName || ''}</span>
    ),
  },
  {
    title: '业态',
    key: 'businessName',
    render: (params, row) => (
      <span>{row.busContractStore.businessName || ''}</span>
    ),
  },
  {
    title: '合同编号',
    align: 'center',
    key: 'contractNumber',
  },
  {
    title: '签约人',
    key: 'contacts',
    render: (params, row) => (
      <span>{row.busContractStore.contacts || ''}</span>
    ),
  },
  {
    title: '签订时间',
    key: 'signTime',
  },
  {
    title: '状态',
    key: 'status',
    render: params => (
      <span>{types[params]}</span>
    ),
  },
  {
    title: '租金总金额（元）',
    align: 'center',
    key: 'rentSumMoney',
  },
  {
    title: '物业费总金额（元）',
    align: 'center',
    key: 'propertySumMoney',
  },
  {
    title: '已收总金额（元）',
    align: 'center',
    key: 'collectMoney',
  },
  {
    title: '到期时间',
    align: 'center',
    key: 'hireEnd',
  },
];

const contractListing = props => {
  const { getFieldDecorator } = props.form;
  const [data, setColData] = useState([]);
  const [record, setRecord] = useState([]);
  const [signedTime, setsignedTime] = useState('');
  const [expireTime, setexpireTime] = useState('');
  const [staffList, setStaffList] = useState([]);
  const [listQuery, setListQuery] = useState({
    pageNo: 1,
    pageSize: 10,
  });
  const [info, setInfo] = useState({});
  // 分配\新增角色模态框
  const [isShow, setState] = useState(false);

  // 列表
  const getList = async params => {
    const r = await fetchContract(params);
    if (r.data && r.data.data) {
      setColData(r.data.data);
    }
  };
  useEffect(() => {
    getList(listQuery);
  }, []);

  // 查询
  const searchOneBtn = async params => {
    getList(params);
  };
  // 新增/修改 模态框
  const handleStatus = record => {
    setState(!isShow);
    if (record) {
      setInfo(record)
    }
  };
  const time1 = (v, t) => {
    setsignedTime(v)
    setListQuery({ ...listQuery, StartTime: t[0] })
    setListQuery({ ...listQuery, EndTime: t[1] })
  }
  const time2 = (v, t) => {
    setexpireTime(v)
    setListQuery({ ...listQuery, expireStartTime: t[0] })
    setListQuery({ ...listQuery, expireEndTime: t[1] })
  }
  // 查询表单
  const getFields = () => (
    <Col span={18}>
      <Col span={8}>
        <Form.Item label="模糊条件">
          <Input onChange={v => { setListQuery({ ...listQuery, condition: v.target.value }) }} placeholder="主题，合同编号" value={listQuery.condition} />
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="状态">
          <Select onChange={v => { setListQuery({ ...listQuery, status: v }) }} placeholder="选择状态" value={listQuery.status}>
            { statsList.map(v => (<Option key={v.value}>{v.label}</Option>)) }
          </Select>
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="签订时间">
          <RangePicker value={signedTime} onChange={time1} />
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="到期时间">
          <RangePicker value={expireTime} onChange={time2} />
        </Form.Item>
      </Col>
    </Col>
  );
  // 查询表单逻辑
  const handleSearch = e => {
    e.preventDefault()
    searchOneBtn(listQuery);
  };

  // 表单提交
  const handleSubmit = e => {
    e.preventDefault();
    props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const params = values
        params.status ? params.status = '1' : params.status = '0'
        console.log('Received values of form: ', values);
        // saveSupplier({ storeBusiness: params }).then(() => {
        //   getList(listQuery)
        //   setState(!isShow);
        // })
      }
    });
  };
  // 清空查询条件
  const handleReset = () => {
    const aobj = {
      pageNo: 1,
      pageSize: 10,
    }
    setListQuery(aobj)
    getList(aobj)
  };
  // 按钮逻辑
  const handleBtn = type => {
    if (record.length !== 1 && type !== 1) return message.warning('请勾选一条数据！');
    switch (type) {
      // 新增
      case 1:
        return handleStatus();
      // 查询
      case 2:
        return handleSearch();
      case 3:
        return handleStatus(record[0]);
      case 5:
        router.push({ pathname: '/rentCenter/contractManage/contractDetail', query: { i: record[0].id } });
        break
      default:
        return ''
    }
  };
  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      setRecord(selectedRows)
    },
  };
  return (
    <PageHeaderWrapper>
      {/* 查询条件 */}
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <Table columns={columns} dataSource={hasSearchBtn ? data : data} rowSelection={rowSelection} rowKey={record => record.id} />
      {/* 新增/修改 */}
      <Modal
        title="新增/修改"
        visible={isShow}
        onOk={handleSubmit.bind(this)}
        onCancel={handleStatus.bind(this)}
        destroyOnClose
      >
        <Form {...formItemLayout}>
          <Form.Item label="商户名称">
            {getFieldDecorator('merchantName', {
              initialValue: info.merchantName || '',
              rules: [
                {
                  required: true,
                  message: '请输入商户名称',
                },
              ],
            })(<Input placeholder="请输入商户名称" />)}
          </Form.Item>
          <Form.Item label="商户编号">
            {getFieldDecorator('merchantsNum', {
              initialValue: info.merchantsNum || '',
            })(<Input disabled />)}
          </Form.Item>
          <Form.Item label="法人">
            {getFieldDecorator('legalPerson', {
              initialValue: info.legalPerson || '',
              rules: [
                {
                  required: true,
                  message: '请输入法人',
                },
              ],
            })(<Input placeholder="请输入法人" />)}
          </Form.Item>
          <Form.Item label="身份证号码">
            {getFieldDecorator('legalPersonIdNo', {
              initialValue: info.legalPersonIdNo || '',
              rules: [
                {
                  required: true,
                  message: '请输入身份证号码',
                },
              ],
            })(<Input placeholder="请输入身份证号码" />)}
          </Form.Item>
          <Form.Item label="法人手机">
            {getFieldDecorator('legalPhone', {
              initialValue: info.legalPhone || '',
              rules: [
                {
                  required: true,
                  message: '请输入法人手机',
                },
              ],
            })(<Input placeholder="请输入法人手机" />)}
          </Form.Item>
          <Form.Item label="招商员">
            {getFieldDecorator('staffId', {
              initialValue: info.staffId || '',
              rules: [
                {
                  required: true,
                  message: '请选择招商员',
                },
              ],
            })(<Select placeholder="请选择招商员">{ staffList.map(v => (<Option key={v.id}>{v.name}</Option>)) }</Select>)}
          </Form.Item>
          <Form.Item label="通讯地址">
            {getFieldDecorator('contactAddress', {
              initialValue: info.contactAddress || '',
              rules: [
                {
                  required: true,
                  message: '请输入通讯地址',
                },
              ],
            })(<Input placeholder="请输入通讯地址" />)}
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default connect(({ role, global }) => ({
  role,
  hasSearchBtn: global.hasSearchBtn,
}))(Form.create()(contractListing));
